package com.szholly.pro.watergas_server.ps.controller;

import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.szholly.pro.watergas_server.common.data.DataUtil;
import com.szholly.pro.watergas_server.common.util.JsonUtil;
import com.szholly.pro.watergas_server.common.web.BaseController;
import com.szholly.pro.watergas_server.common.web.RequestUnit;
import com.szholly.pro.watergas_server.ps.service.CommonService;
import com.szholly.pro.watergas_server.ps.service.MaterialReplaceService;
import com.szholly.utils.spring.SpringBeanFactory;
import com.szholly.data.general.ITable;
import com.szholly.data.general.ITableFactory;
import com.szholly.data.general.PageInfo;
import com.szholly.data.general.RowBase;
import com.szholly.plug.form.excel.utils.StringUtil;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("/MaterialReplace/*")
public class OperationMaterialReplaceController extends BaseController {

	protected final static Logger logger = LoggerFactory.getLogger(OperationMaterialReplaceController.class);

	@Autowired
	CommonService commonService;

	@Autowired
	MaterialReplaceService materialReplaceService;

	/**
	 * 获取设备部件/耗材更换记录
	 * 
	 * @param resq
	 * @param res
	 * @throws Exception
	 */
	@RequestMapping(value = "/getMaterialReplaceList")
	public void getMaterialReplaceList(HttpServletRequest resq, HttpServletResponse res) throws Exception {
		Map<String, String> params = getParams();
		PageInfo pageInfo = DataUtil.getPageInfo();
		List<RowBase> list = materialReplaceService.getMaterialReplaceList(params, pageInfo);
		JSONObject json = DataUtil.listToJSONObject(list, null, pageInfo);
		String result = json.toString();
		outString(result);
	}
	/**
	 * 获取设备部件/耗材更换记录(地表水)
	 * 
	 * @param resq
	 * @param res
	 * @throws Exception
	 */
	@RequestMapping(value = "/getSWMaterialReplaceList")
	public void getSWMaterialReplaceList(HttpServletRequest resq, HttpServletResponse res) throws Exception {
		Map<String, String> params = getParams();
		PageInfo pageInfo = DataUtil.getPageInfo();
		List<RowBase> list = materialReplaceService.getSWMaterialReplaceList(params, pageInfo);
		JSONObject json = DataUtil.listToJSONObject(list, null, pageInfo);
		String result = json.toString();
		outString(result);
	}
	/**
	 * 耗材统计
	 * @param resq
	 * @param res
	 * @throws Exception
	 */
	@RequestMapping(value="/StatisticsEquipment")
	public void StatisticsEquipment(HttpServletRequest resq,HttpServletResponse res) throws Exception{
		HashMap<String,Object> queryobject=RequestUnit.getHashMapParmO();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		//获取当前月
		long l = System.currentTimeMillis();
		Date date = new Date(l);
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");		
		//获取当前月的最后一天
		Calendar calendar = Calendar.getInstance();  
		calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));  
		
		String station_id=(String) queryobject.get("queryObject[STATION_ID]");
		String startDate=(String) queryobject.get("objdata[startDate]");
		String endDate=(String) queryobject.get("objdata[endDate]");
		long day=0;
		//计算天数
		if(StringUtil.IsNotNullOrEmpty(startDate)&&StringUtil.IsNotNullOrEmpty(endDate)){
			//总秒数
			long miao=format.parse(endDate).getTime()-format.parse(startDate).getTime();
			day=miao/1000/60/60/24;//总秒数/毫秒/秒/分钟/小时=天数
		}
		Map<String,String> params=new HashMap<>();//查询条件		
		HashMap<String, Object> data = new HashMap<>();		
		if(StringUtil.IsNotNullOrEmpty(station_id)){
			params.put("station_id", station_id);
		}	
		if(StringUtil.IsNotNullOrEmpty(startDate)){
			params.put("start",startDate);
		}
		if(StringUtil.IsNotNullOrEmpty(endDate)){
			params.put("end",endDate);
		}
		if(StringUtil.IsNotNullOrEmpty(dateFormat.format(date))){
			params.put("atStart",dateFormat.format(date));
		}
		if(StringUtil.IsNotNullOrEmpty(format.format(calendar.getTime()))){
			params.put("atEnd",format.format(calendar.getTime()));
		}
		data=EquipmentTool(params,day);
		String jsonResult = JsonUtil.ConvertObjectToJson(data);
		outString(jsonResult);
	}
	/**
	 * 耗材统计导出PDF文档
	 * @param resq
	 * @param res
	 * @throws Exception
	 */
	@RequestMapping(value="EquipmentexportPDF")
	public void EquipmentexportPDF(HttpServletRequest resq,HttpServletResponse res) throws Exception{
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String station_id=RequestUnit.getString("STATION_ID");
		String start=RequestUnit.getString("startDate");
		String end=RequestUnit.getString("endDate");
		String dataType=RequestUnit.getString("dataType");
		String Monthstart=RequestUnit.getString("startMonthstart");
		String Monthend=RequestUnit.getString("startMonthend");
		//获取当前月
		long l = System.currentTimeMillis();
		Date date = new Date(l);
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");		
		//获取当前月的最后一天
		Calendar calendar = Calendar.getInstance();  
		calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));  
		
		Map<String,String> params=new HashMap<>();//查询条件	
		long day=0;
		//计算天数
		if(StringUtil.IsNotNullOrEmpty(start)&&StringUtil.IsNotNullOrEmpty(end)){
			//总秒数
			long miao=format.parse(end).getTime()-format.parse(start).getTime();
			day=miao/1000/60/60/24;//总秒数/毫秒/秒/分钟/小时=天数
		}
		HashMap<String, Object> Replacedata = new HashMap<>();
		if(StringUtil.IsNotNullOrEmpty(start)){
			params.put("start",start);
		}
		if(StringUtil.IsNotNullOrEmpty(end)){
			params.put("end",end);
		}
		if(StringUtil.IsNotNullOrEmpty(station_id)){
			params.put("station_id", station_id);
		}
		if(StringUtil.IsNotNullOrEmpty(dateFormat.format(date))){
			params.put("atStart",dateFormat.format(date));
		}
		if(StringUtil.IsNotNullOrEmpty(format.format(calendar.getTime()))){
			params.put("atEnd",format.format(calendar.getTime()));
		}
		//获取仪器信息
		Replacedata=EquipmentTool(params,day);
		HashMap<String, Object> data = new HashMap<>();
		if(Integer.parseInt(Monthstart)>=2&&Integer.parseInt(Monthend)<=4){
			data.put("quarter", "(第四季度)");
		}else if(Integer.parseInt(Monthstart)>=5&&Integer.parseInt(Monthend)>=7){
			data.put("quarter", "(第一季度)");
		}else if(Integer.parseInt(Monthstart)>=8&&Integer.parseInt(Monthend)<=10){
			data.put("quarter", "(第二季度)");
		}else{			
			data.put("quarter", "(第三季度)");
		}
		data.put("Replacedata", Replacedata);
		data.put("start", start);
		data.put("end", end);
		data.put("dataType", dataType);
		data.put("monthstart", Monthstart);
		data.put("monthend", Monthend);
		outPDF(data, "equipmentStatistics.html", "仪器耗材统计.pdf",false);
	}
	/**
	 * 耗材统计数据源
	 * @return
	 */
	public HashMap<String,Object> EquipmentTool(Map<String,String> params,long day){
		HashMap<String, Object> data = new HashMap<>();
		NumberFormat nt = NumberFormat.getPercentInstance();
		//获取仪器信息
		List<RowBase> listEquipment=materialReplaceService.StatisticsEquipment(params, null);//仪器
		List<RowBase> listReplace=materialReplaceService.StatisticsReplace(params, null);//耗材记录
/*		//获取其它仪器耗材信息
		params.put("Other", "其他");
		List<RowBase> listEquipmentOther=materialReplaceService.StatisticsEquipment(params, null);//仪器
		List<RowBase> listReplaceOther=materialReplaceService.StatisticsReplace(params, null);//耗材记录
*/		Double QualifiedSum=0.0;
		List<Object> list=new ArrayList<>();
		for(RowBase row:listReplace){
			//判断仪器名称是否为空
			if(row.getSafeString("DEVICE_NAME")!=null&&!"".equals(row.getSafeString("DEVICE_NAME"))){
				HashMap<String, Object> dataReplace = new HashMap<>();
				if(day<=31){//如果统计天数小于或等于31天，视为月统计
					//当每月需耗材量小于等于实际耗材量，属于合格
					if((row.getSafeInt("REPLACE_COUNT_YEAR")/12)<=row.getSafeInt("MATERIAL_COUNT")){
						dataReplace.put("CONDITION","合格");
						QualifiedSum=QualifiedSum+1;
					}else{
						dataReplace.put("CONDITION","不合格");
					}
				}else if(day>31&&day<94){//如果统计天数大于31天河小于94天，视为季度统计
					//当每季度需耗材量小于等于实际耗材量，属于合格
					if((row.getSafeInt("REPLACE_COUNT_YEAR")/4)<=row.getSafeInt("MATERIAL_COUNT")){
						dataReplace.put("CONDITION","合格");
						QualifiedSum=QualifiedSum+1;
					}else{
						dataReplace.put("CONDITION","不合格");
					}
				}else if(day>93&&day<=366){//如果统计天数大于93天河小于等于366天，视为年度统计
					if(row.getSafeString("REPLACE_COUNT_YEAR")!=null){
						//当每年度需耗材量小于等于实际耗材量，属于合格
						if(row.getSafeInt("REPLACE_COUNT_YEAR")<=row.getSafeInt("MATERIAL_COUNT")){
							dataReplace.put("CONDITION","合格");
							QualifiedSum=QualifiedSum+1;
						}else{
							dataReplace.put("CONDITION","不合格");
						}
							}
						}
						dataReplace.put("ReplaceList", row);
						list.add(dataReplace);
					}
				}
				if(QualifiedSum>0){
					if(QualifiedSum>list.size()){
						data.put("Acceptability","100%");//合格率
						data.put("RejectRatio","0.00%");//不合格率
					}else{
						data.put("Acceptability",nt.format(QualifiedSum/list.size()));//合格率
						data.put("RejectRatio",nt.format((list.size()-QualifiedSum)/list.size()));//不合格率
					}
				}else{
					data.put("Acceptability","0.00%");//合格率
					data.put("RejectRatio","100%");//不合格率
				}
				if(list.size()<=0){
					data.put("RejectRatio","0.00%");//不合格率
				}
				data.put("FailSum",Math.floor(list.size()-QualifiedSum));//不合格总数量		
				data.put("QualifiedSum",Math.floor(QualifiedSum));//合格总数量	
				data.put("Equipment", listEquipment);
/*				data.put("listEquipmentOther", listEquipmentOther);
				data.put("listReplaceOther", listReplaceOther);*/
				data.put("Replace", list);
		return data;
	}
	/**
	 * 耗材信息列表
	 * @param resq
	 * @param res
	 * @throws Exception
	 */
	@RequestMapping(value="queryOperationMaterial")
	public void queryOperationMaterial(HttpServletRequest resq,HttpServletResponse res) throws Exception{
		Map<String,String> params=new HashMap<>();//查询条件	
		PageInfo pageInfo = DataUtil.getPageInfo();
		List<RowBase> materialList=materialReplaceService.qeuryOperationMaterial(params, pageInfo);
		JSONObject JSON=DataUtil.listToJSONObject(materialList, null, pageInfo);
		outString(JSON.toString());
	}
	/**
	 * 获得名称
	 * @param resq
	 * @param res
	 * @throws Exception
	 */
	@RequestMapping(value="getMaterialName")
	public void getMaterialName(HttpServletRequest resq, HttpServletResponse res) throws Exception{
		Map<String,String> result=new HashMap<>();
		List<RowBase> list=materialReplaceService.getMaterialNameService(result, null);
		Map<String,Object> rowresult=new HashMap<>();
		rowresult.put("data", list);
		JSONObject json=DataUtil.listToJSONObject(list);
		outString(json.toString());
	}
	/**
	 * 获得编号
	 * @param resq
	 * @param res
	 * @throws Exception
	 */
	@RequestMapping(value="getManufacterCode")
	public void getManufacterCode(HttpServletRequest resq, HttpServletResponse res) throws Exception{
		Map<String,String> result=new HashMap<>();
       String material_name = RequestUnit.getParameter("MATERIAL_NAME");
		if (StringUtil.IsNotNullOrEmpty(material_name)) {
			result.put("material_name", material_name);
		}
		List<RowBase> list=materialReplaceService.getManufacterCodeService(result, null);
		Map<String,Object> rowresult=new HashMap<>();
		rowresult.put("data", list);
		JSONObject json=DataUtil.listToJSONObject(list);
		outString(json.toString());
	}
	/**
	 * 获取品牌名称
	 * @param resq
	 * @param res
	 * @throws Exception
	 */
	@RequestMapping(value="getManufacterName")
	public void getManufacterName(HttpServletRequest resq, HttpServletResponse res) throws Exception{
		Map<String,String> result=new HashMap<>();
		List<RowBase> list=materialReplaceService.getManufacterNameService(result, null);
		Map<String,Object> rowresult=new HashMap<>();
		rowresult.put("data", list);
		JSONObject json=DataUtil.listToJSONObject(list);
		outString(json.toString());
	}
	/**
	 * 获得型号
	 * @param resq
	 * @param res
	 * @throws Exception
	 */
	@RequestMapping(value="getManufacterType")
	public void getManufacterType(HttpServletRequest resq, HttpServletResponse res) throws Exception{
		Map<String,String> result=new HashMap<>();
       String manufacturer = RequestUnit.getParameter("MANUFACTURER");
		if (StringUtil.IsNotNullOrEmpty(manufacturer)) {
			result.put("manufacturer", manufacturer);
		}
		List<RowBase> list=materialReplaceService.getManufacterTypeService(result, null);
		Map<String,Object> rowresult=new HashMap<>();
		rowresult.put("data", list);
		JSONObject json=DataUtil.listToJSONObject(list);
		outString(json.toString());
	}
	/**
	 * 耗材信息编辑
	 * @param resq
	 * @param res
	 * @throws Exception
	 */
	@RequestMapping(value="updateOperationMaterial")
	public void updateOperationMaterial(HttpServletRequest resq,HttpServletResponse res) throws Exception{
		HashMap<String,Object> params=RequestUnit.getHashMapParmO();
		ITableFactory tableFactory = (ITableFactory) SpringBeanFactory.getBean("TableFactory");
		ITable pTable = tableFactory.openTable("operation_material");
		materialReplaceService.updateOperationMaterial(params, pTable);
	}
	/**
	 * 添加耗材信息
	 * @param resq
	 * @param res
	 * @throws Exception
	 */
	@RequestMapping(value="insertOperationMaterial")
	public void insertOperationMaterial(HttpServletRequest resq,HttpServletResponse res) throws Exception{
		HashMap<String,Object> params=RequestUnit.getHashMapParmO();
		ITableFactory tableFactory = (ITableFactory) SpringBeanFactory.getBean("TableFactory");
		ITable pTable = tableFactory.openTable("operation_material");
		materialReplaceService.addOperationMaterial(pTable.getTableName(), params);
	}
	
	private Map<String,String> getParams(){
		Map<String, String> params = new HashMap<String, String>();
		
		String strTASK_ID = RequestUnit.getString("TASK_ID");
		if (StringUtil.IsNotNullOrEmpty(strTASK_ID)) {
			params.put("task_code", strTASK_ID);
		}
		String strWWTP_ID = RequestUnit.getString("WWTP_ID");
		if (StringUtil.IsNotNullOrEmpty(strWWTP_ID)) {
			params.put("wwtp_id", strWWTP_ID);
		}
		String strFLOW_NAME = RequestUnit.getString("FLOW_NAME");
		if (StringUtil.IsNotNullOrEmpty(strFLOW_NAME)) {
			params.put("flow_type", strFLOW_NAME);
		}
		String water_type = RequestUnit.getString("WATER_TYPE");
		if (StringUtil.IsNotNullOrEmpty(water_type)) {
			params.put("water_type", water_type);
		}
		String station_id = RequestUnit.getString("STATION_ID");
		if (StringUtil.IsNotNullOrEmpty(station_id)) {
			params.put("station_id", station_id);
		}
		String station_name = RequestUnit.getString("STATION_NAME");
		if (StringUtil.IsNotNullOrEmpty(station_name)) {
			params.put("station_name", station_name);
		}
		String strMATERIAL_NAME = RequestUnit.getString("MATERIAL_NAME");
		if (StringUtil.IsNotNullOrEmpty(strMATERIAL_NAME)) {
			String mn = StringUtil.joinForSQL(strMATERIAL_NAME.split(","), ",");
			params.put("material_names", "(" + mn + ")");
		}
		String strREPLACE_DATE_FROM = RequestUnit.getString("REPLACE_DATE_FROM");
		if (StringUtil.IsNotNullOrEmpty(strREPLACE_DATE_FROM)) {
			params.put("start", strREPLACE_DATE_FROM);
		}
		String strREPLACE_DATE_TO = RequestUnit.getString("REPLACE_DATE_TO");
		if (StringUtil.IsNotNullOrEmpty(strREPLACE_DATE_TO)) {
			params.put("end", strREPLACE_DATE_TO);
		}
		return params;
	}

	/**
	 * 导出耗材备件更换报表
	 * 
	 * @param resq
	 * @param res
	 * @throws Exception
	 */
	@RequestMapping(value = "/exportDoc")
	public void exportDoc(HttpServletRequest resq, HttpServletResponse res) throws Exception {
		Map<String, String> params = getParams();

		Map<String, Object> root = new HashMap<String, Object>();
		List<RowBase> list = materialReplaceService.getMaterialReplaceList(params, DataUtil.getPageInfo());
		root.put("list", list);
		RowBase row = null;
		
		String OUNAME = "";
		if (params.containsKey("station_id")) {
			OUNAME = commonService.getOperationUnitByStaionId(params.get("station_id"));
		} else if (params.containsKey("wwtp_id")) {
			OUNAME = commonService.getOperationUnit(params.get("wwtp_id"));
		}
		root.put("OUNAME", OUNAME);

		if (params.containsKey("station_id")) {
			row = commonService.getStationGroupInfo(params.get("station_id"));
			if (row != null) {
				root.put("GROUP_LEADER", row.getSafeString("GROUP_LEADER"));
			}
			root.put("STATION_NAME", params.get("station_name"));
		} else {
			row = commonService.getStation(params.get("wwtp_id"), params.get("flow_type"));
			if(row!=null){
				String stationName = row.getSafeString("NAME");
				String stationId = row.getSafeString("CODE");
				root.put("STATION_NAME",stationName);
				row = commonService.getStationGroupInfo(stationId);
				if(row!=null){
					root.put("GROUP_LEADER",row.getSafeString("GROUP_LEADER"));
				}
			}
		}

		outWord(root, "replacement.xml", "耗材/备件更换记录表.doc");
	}
	
	/**
	 * 导出耗材备件更换报表(地表水)
	 * 
	 * @param resq
	 * @param res
	 * @throws Exception
	 */
	@RequestMapping(value = "/exportSWDoc")
	public void exportSWDoc(HttpServletRequest resq, HttpServletResponse res) throws Exception {
		Map<String, String> params = getParams();

		Map<String, Object> root = new HashMap<String, Object>();
		List<RowBase> list = materialReplaceService.getSWMaterialReplaceList(params, DataUtil.getPageInfo());
		root.put("list", list);
		if(list!=null && list.size()>0) {
			RowBase row = list.get(0);
			root.put("USERNAME",row.getSafeString("USER_NAME"));
			root.put("STATION_NAME",row.getSafeString("STATION_NAME"));
			
		}
		RowBase row = null;
		
		String OUNAME = "";
		if (params.containsKey("station_id")) {
			OUNAME = commonService.getOperationUnitByStaionId(params.get("station_id"));
		} else if (params.containsKey("wwtp_id")) {
			OUNAME = commonService.getOperationUnit(params.get("wwtp_id"));
		}
		root.put("OUNAME", OUNAME);

		if (params.containsKey("station_id")) {
			row = commonService.getStationGroupInfo(params.get("station_id"));
			if (row != null) {
				root.put("GROUP_LEADER", row.getSafeString("GROUP_LEADER"));
			}
			root.put("STATION_NAME", params.get("station_name"));
		} else {
			row = commonService.getStation(params.get("wwtp_id"), params.get("flow_type"));
			if(row!=null){
				String stationName = row.getSafeString("NAME");
				String stationId = row.getSafeString("CODE");
				root.put("STATION_NAME",stationName);
				row = commonService.getStationGroupInfo(stationId);
				if(row!=null){
					root.put("GROUP_LEADER",row.getSafeString("GROUP_LEADER"));
				}
			}
		}

		outWord(root, "sw/replacement.xml", "耗材/备件更换记录表.doc");
	}
	
	/**
	 * 获取耗材更换记录数
	 * @param resq
	 * @param res
	 * @throws Exception
	 */
	@RequestMapping(value = "/getReplacementCount")
	public void getReplacementCount(HttpServletRequest resq, HttpServletResponse res) throws Exception {
		Map<String, String> params = getParams();
		int count = materialReplaceService.getReplacementCount(params);
		
		JSONObject obj = new JSONObject();
		obj.put("count", count);
		outString(obj.toString());
	}

	/**
	 * 获取字典项
	 * 
	 * @param resq
	 * @param res
	 * @throws Exception
	 */
	@RequestMapping(value = "/getDataDomain")
	public void getJobList(HttpServletRequest resq, HttpServletResponse res) throws Exception {
		String strDomainName = RequestUnit.getString("DomainName");
		String strSQL = " select * from DATA_DEFULATDOMAIN t where t.S_DOMAINNAME='" + strDomainName + "' ";
		String result = DataUtil.getPageSelectJson(strSQL, null);
		outString(result);
	}

}
